package com.wbt.bambootown.api;

import android.os.Environment;


import com.facebook.stetho.okhttp3.StethoInterceptor;
import com.wbt.bambootown.BuildConfig;
import com.wbt.bambootown.FrameApp;
import com.wbt.bambootown.cons.Cons;
import com.wbt.bambootown.utils.Log;
import com.wbt.bambootown.utils.SPUtils;

import java.io.File;
import java.net.URI;
import java.util.concurrent.TimeUnit;

import me.jessyan.retrofiturlmanager.RetrofitUrlManager;
import okhttp3.Cache;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class ApiWrapper {

    private static final String HTTP_CACHE_DIR = "http";
    public static final int HTTP_CACHE_SIZE = 20 * 1024 * 1024;
    public static final int HTTP_CONNECT_TIMEOUT = 120 * 1000;
    public static final int HTTP_READ_TIMEOUT = 120 * 1000;

    private static Retrofit mRetrofit;
    private static ApiService mApiService;

    public static Retrofit getRetrofit() {
        if (mRetrofit == null) {
            if (mRetrofit == null) {
                OkHttpClient mClient = RetrofitUrlManager.getInstance().with(
                        new OkHttpClient.Builder()
                                .addInterceptor(new LoggerInterceptor("TAG"))
                                .addNetworkInterceptor(new StethoInterceptor())
                                .cache(new Cache(getHttpCacheDir(), HTTP_CACHE_SIZE))
                                .connectTimeout(HTTP_CONNECT_TIMEOUT, TimeUnit.MILLISECONDS)
                                .readTimeout(HTTP_READ_TIMEOUT, TimeUnit.MILLISECONDS)
                                .addInterceptor(new CacheInterceptor())
                )
                        .build();

                mRetrofit = new Retrofit.Builder()
                        .client(mClient)
                        .baseUrl(SPUtils.getString(Cons.SPCons.API_ADDRESS) + "/api/AppData/")
                        .addConverterFactory(GsonConverterFactory.create())
                        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                        .build();
            }
        }
        return mRetrofit;
    }

    public static ApiService getApiService() {
        if (mApiService == null) {
            mApiService = getRetrofit().create(ApiService.class);
        }
        return mApiService;
    }


    public static final File getHttpCacheDir() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return new File(FrameApp.getApplication().getExternalCacheDir(), HTTP_CACHE_DIR);
        }
        return new File(FrameApp.getApplication().getCacheDir(), HTTP_CACHE_DIR);
    }

}
